<template>
	<view class="padding_48rpx">
		<view class="edit flex-start-center padding-left_30rpx">
			<input class="uni-input" v-model="form.name" placeholder="门店名称" />


		</view>
		<view class="edit flex-start-center padding-left_30rpx">
			<input class="uni-input" type="number" maxlength="11" v-model="form.account" placeholder="门店账号" />


		</view>

		<view class="edit flex-start-center padding-left_30rpx" v-if="!isEdit">
			<input class="uni-input" disabled="" v-model="form.role_id" placeholder="门店角色" />
			<picker mode="selector" @change='classifyFn' :range="merchantRoleList" :range-key="'text'">
				<view class="flex">
					<text style="width: 120rpx;">{{merchantRole}}</text>
					<uni-icons type="right" size="15"></uni-icons>
				</view>
			</picker>

		</view>
		<view class="edit flex-start-center padding-left_30rpx">
			<input class="uni-input" v-model="form.real_name" placeholder="姓名" />


		</view>
		<view class="edit flex-start-center padding-left_30rpx">
			<input class="uni-input" type="number" maxlength="11" v-model="form.phone" placeholder="联系电话" />


		</view>
		<view class="edit flex-start-center padding-left_30rpx" v-if="!isEdit">
			<input class="uni-input" password type="text" v-model="form.password" placeholder="门店密码" />


		</view>
		<view class="edit flex-start-center padding-left_30rpx" >
			<input class="uni-input" @focus="selPosition"  type="text" v-model="form.navigation" placeholder="获取定位" />
		
		
		</view>
		<view class="edit flex-start-center padding-left_30rpx">
			<text class="font30" style="color: grey;"></text>
			<pca-picker-cc v-on:getAddressResultObj="getAddressResultObj" :addressList.sync="addressList">
				<view class="uni-input">{{ addressList.join(' ') }}</view>
			</pca-picker-cc>

		</view>
		<view class=" flex-start-center ">
			<textarea v-model="form.address" style="background-color: rgb(246, 248, 255) ;padding: 30rpx;" placeholder="请输入详细地址" />
		</view>

		<sunui-upimg1 class="margin-top_20rpx" :border="'1px dashed #bfbfbf'" :formData="imgFormData"
			:storageMode="storageMode" :header="header" :size="['200rpx', '200rpx']" btnName="上传门店logo"
			:uploadServerUrl="upPicUrl" ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1"
			:maxFileNumber="1"><template v-slot:icon>
				<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
			</template></sunui-upimg1>
		<view class="btnSure flex" @click="editFn()">
			{{isEdit?'编辑':'添加'}}
		</view>

	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {

		},
		data() {
			return {
				tabIndex: 4,


				form: {
					// 店铺名字
					name: '',
					// 手机号
					phone: '',
					// 省id
					province_id: '',
					// 区id
					county_id: '',
					// 市id
					city_id: '',
					// 省
					province_name: '',
					// 市
					city_name: '',
					// 区
					county_name: '',
					// 详细地址
					address: "",
					// 角色id
					role_id: '',
					// 密码
					password: '',
					// 姓名
					real_name: '',
					// 门店账号
					account: '',
					//logo图
					logo: '',
					navigation:'',
					longitude:'',
					dimension:''

				},
				imgFormData: null,
				ossInfo: null,
				upPicUrl: null,
				imgStr: [],

				storageMode: "2",
				header: null,
				token: uni.getStorageSync('login').token,
				isEdit: false,
				addressList: ["", "", ""],
				merchantRole: '请选择角色',
				merchantRoleList: []
			}
		},
		onLoad(options) {

			if (options.id) {

				this.form.id = ''
				this.form.sort = ''
				this.$sun.assignObject(this.form, {
					...options
				})
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.setItems([options.logo]);
				})


				this.isEdit = true
				console.log(this.form)

			}
		},
		onShow() {
			this.init()
			this.$at.releaseKey('submit');
		},
		methods: {
			selPosition(e){
				// console.log(e)
	
					uni.chooseLocation({
						success: res => {
							this.form.navigation = res.name;
							this.form.dimension = res.longitude;
							this.form.longitude = res.latitude ;
							console.log('获取定位信息res============', res);
						}
					});
				
			},
			async init() {
				// 查询分类列表
				const result = await this.$http.get({
					url: this.$api.merchantRole,
					data: {

                         
					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {
					const classifyData = result.data.map((item) => {
						return {
							text: item.name,
							value: item.id
						}
					})
					this.merchantRoleList = classifyData

					if (this.isEdit) {
						const merchantRole = this.merchantRoleList.find((item) => {

							return item.value == this.form.role_id
						})
						console.log(classifyType)
						this.merchantRole = merchantRole.text
					}

				} else {
					this.$sun.toast(result.msg, 'none')
				}


			},
			classifyFn(e) {

				this.form.role_id = this.merchantRoleList[e.detail.value].value
				console.log(this.form.role_id)
				this.merchantRole = this.merchantRoleList[e.detail.value].text
			},
			// 
			getAddressResultObj(e) {
				//获取详细的 省/市/区 对象信息,更新时被动调,主动调用请自行设置ref值,方法一致
				console.log(e)
				this.form.city_name=e.city.name
				this.form.city_id=e.city.code
				this.form.county_name=e.county.name
				this.form.county_id=e.county.code
				this.form.province_name=e.province.name
				this.form.province_id=e.province.code
				
			},
			async editFn() {
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						if (!this.form.name) {
							this.$sun.toast('请填写门店名称', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.account) {
							this.$sun.toast('请填写门店账号', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.logo) {
							this.$sun.toast('请上传门店logo', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.role_id&&!this.isEdit) {
							this.$sun.toast('请选择门店角色', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.address) {
							this.$sun.toast('请填写详情地址', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.real_name) {
							this.$sun.toast('请填写电话', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.phone) {
							this.$sun.toast('请填写姓名', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.password&&!this.isEdit) {
							this.$sun.toast('请填写密码', 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.navigation) {
							this.$sun.toast('请获取导航地址', 'none')
							this.$at.releaseKey('submit');
						} else {
							const apiuse= this.isEdit? this.$api.editStore:this.$api.addStore
							const result = await this.$http.post({
								url: apiuse,
								data: {
									...this.form
						
								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}
						
							})
							if (result.code == 0) {
								this.$sun.toast(result.msg, 'none')
								this.$at.releaseKey('submit');
								setTimeout(() => {
									this.$sun.navBack()
								}, 800)
							} else {
								this.$sun.toast(result.msg, 'none')
								this.$at.releaseKey('submit');
							}
						}
					}
				})


			},
			// niuyun
			niuyunLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file)
				let fileUrl = file[i].url;
				this.upPicUrl = this.$api.qnyOssSignature;
				let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
				this.imgFormData = {
					file: fileUrl,
					getsize: file.size,
					getContentType: ['image/png', 'image/jpeg'],
					getoriginalfilename: filesNmae,
					getName: filesNmae
				};
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.upload(); //图片上传
				});
				setTimeout(() => {
					this.niuyunLoop(file, i + 1);
				}, 2500);

			},
			delayLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file.length + '===chand1')
				if (file.length) {
					let fileUrl = file[i].url;
					console.log(fileUrl)
					this.timeDate = new Date().getTime();
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀


					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});

				} else {
					this.form.logo = ''
				}

				setTimeout(() => {
					this.delayLoop(file, i + 1);
				}, 500);
			},
			// 上传图片返回
			imgLoaded1(e) {
				console.log(e)

				this.img = [];
				for (let i = 0; i < e.length; i++) {
					this.img.push(e[i].url);
				}


				this.imgStr = this.img

				this.form.logo = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			// “上传图片”发生改变
			imgsChange1(file) {

				console.log('上传发生改变this.storageMode1111============', this.storageMode, '参数file', file);
				
			
					if (file.length) {
						this.upPicUrl = this.$api.upload;
						let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
						this.imgFormData = {
							file: file,
							getsize: file.size,
							getContentType: ['image/png', 'image/jpeg'],
							getoriginalfilename: filesNmae,
							getName: filesNmae
						};
						this.$nextTick(() => {
							this.$refs.selectimgandupload1.upload(); //图片上传
						});
					} else {
						this.form.logo = '',
							this.imgStr = []
					}
					// this.niuyunLoop(file,0)
				
			},
			// 阿里云上传
			async userOssSignature(file) {
				// 文件名
				if (file.length) {
					console.log('this阿里云上传进入=======');
					const ts = new Date().getTime();
					const us = {
						ts
					};
					// let url = this.$api.alyOssSignature + `${object2Url(us)}`;
					let url = 'https://yjykmaster.admin168.net/door-massage/massage/upload/alyOssSignature' +
						`${object2Url(us)}`;

					const res = await this.$http.get({
						url: url,
						data: {
							us: us
						}
					});
					this.ossInfo = res.data;
					this.upPicUrl = this.ossInfo?.host;
					// 获取上传图片名称和后缀
					this.delayLoop(file, 0);
				} else {
					this.form.logo = '',
						this.imgStr = []
				}




			},
		}
	}
</script>

<style lang="less" scoped>
	.edit {
		margin-bottom: 30rpx;
		height: 108rpx;
		background: rgb(246, 248, 255);



	}

	.btnSure {
		z-index: 9999;
		width: 655rpx;
		height: 76rpx;
		background: rgb(81, 142, 247);
		color: rgb(255, 255, 255);
		border-radius: 108rpx;
		font-size: 32rpx;
		font-weight: 700;
		position: fixed;
		bottom: 20rpx;
	}

	page {
		background: #fff;
	}
</style>